package net.didactylos.helpline.stripes.security;

import java.lang.reflect.*;

import net.didactylos.helpline.action.*;
import net.didactylos.helpline.data.User;
import net.didactylos.helpline.stripes.bean.HelplineActionBeanContext;
import net.sourceforge.stripes.action.*;
import net.sourceforge.stripes.controller.*;
import net.sourceforge.stripes.util.Log;

@Intercepts(LifecycleStage.HandlerResolution)
public class SecurityInterceptor implements Interceptor
{
	public Resolution intercept(ExecutionContext context) throws Exception
	{
		Log log = Log.getInstance(SecurityInterceptor.class);
		log.trace("Intercepted request");
		Resolution resolution = context.proceed();

		User user = ((HelplineActionBeanContext) context.getActionBeanContext())
			.getUser();
		
		if (user == null)
		{
			user = User.NOBODY;
		}
		
		Method method = context.getHandler();
		
		Secured secured = method.getAnnotation(Secured.class);
		
		if (secured != null)
		{
			log.debug("Secured attribute found: ", secured.value());
			
			if (user.hasCapability(secured.value().capabilities()))
			{
				// Inject capability somewhere for later use?
				// Continue processing request:
				log.debug("Proceeding with default resolution");
				return resolution;
			}
		}
		else
		{
			log.warn("Secured attribute not found for handler: ", method.toString());
		}

		log.info("Insufficient rights. Redirecting to sign-in page.");
		// Display message?
        return new RedirectResolution(SigninAction.class);
	}
}
